package com.qfedu.labsystem.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.qfedu.labsystem.entity.bo.UserBO;
import com.qfedu.labsystem.entity.dto.CsvUserDTO;
import com.qfedu.labsystem.entity.dto.ImportUserDTO;
import com.qfedu.labsystem.service.UploadService;
import com.qfedu.labsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName UploadServiceImpl
 * @Author ykx
 * @Date 2024/4/8 16:51
 * @Version 1.0
 */
@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private UserService userService;

    @Override
    public void upload(MultipartFile file) throws Exception {
        String fileName = "bg.jpg";
        String filePath = ResourceUtils.getURL("classpath:").getPath() + "static/upload/";
        File dist = new File(filePath + fileName);
        if (!dist.getParentFile().exists()) {
            dist.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dist);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public String importExcel(MultipartFile file) throws IOException {
        List<UserBO> userList = new ArrayList<>();

        InputStream inputStream = file.getInputStream();
        ExcelReaderBuilder excelReaderBuilder = EasyExcel.read(inputStream, ImportUserDTO.class, new AnalysisEventListener<ImportUserDTO>() {
            /**
             * 每读一行会自动调用这个方法
             *
             * @param importUserDTO   读取的内容封装成此对象
             * @param analysisContext
             */
            @Override
            public void invoke(ImportUserDTO importUserDTO, AnalysisContext analysisContext) {
                UserBO userBO = new UserBO();
                userBO.setUsername(importUserDTO.getUsername());
                userBO.setPassword(importUserDTO.getPassword());
                userBO.setTel(importUserDTO.getTel());
                userBO.setEmail(importUserDTO.getEmail());
                userBO.setRoleId(importUserDTO.getRoleId());
                userList.add(userBO);
            }

            /**
             * 全部读完之后调用的方法
             *
             * @param analysisContext
             */
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                userService.saveBatch(userList);
            }
        });
        //获取一个工作表
        ExcelReaderSheetBuilder sheet = excelReaderBuilder.sheet();
        //读取工作表内容:sheet方法参数：工作表的顺序号（从0开始）或者工作表的名字，不传默认为0
        sheet.doRead();
        return "导入成功";
    }

    @Override
    public String importCsv(MultipartFile file) {
        try (BufferedReader fileReader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
            CsvToBean<CsvUserDTO> csvToBean = new CsvToBeanBuilder<CsvUserDTO>(fileReader)
                    .withType(CsvUserDTO.class)
                    .withSkipLines(1)
                    .withIgnoreLeadingWhiteSpace(true)
                    .build();

            List<CsvUserDTO> list = csvToBean.parse();

            List<UserBO> userBOList = list.stream()
                    .map(user -> {
                        UserBO userBO = new UserBO();
                        userBO.setUsername(user.getUsername());
                        userBO.setPassword(user.getPassword());
                        userBO.setRoleId(user.getRoleId());
                        userBO.setEmail(user.getEmail());
                        userBO.setTel(user.getTel());
                        return userBO;
                    })
                    .collect(Collectors.toList());


            userService.saveBatch(userBOList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "导入成功";
    }

    @Override
    public String uploadImage(MultipartFile file, Integer id) throws Exception {
        // 获取文件名
        String filename = System.currentTimeMillis() + file.getOriginalFilename();

        String filePath = ResourceUtils.getURL("classpath:").getPath() + "static/image/";
        File dist = new File(filePath + filename);
        if (!dist.getParentFile().exists()) {
            dist.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dist);

            // 设置图片路径为用户头像的url地址
            UserBO userBO = userService.getById(id);
            userBO.setImageUrl(filename);
            userService.updateById(userBO);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return filename;
    }
}
